﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace GiveAQuiz.Web.Helpers
{
  /// <summary>
  /// Extension methods for the String class.
  /// </summary>
  public static class StringExtensions
  {
    /// <summary>
    /// Extension method that converts a String to a byte array 
    /// using UTF8 Encoding.
    /// </summary>
    /// <param name="s">The String for which to generate the 
    /// byte array.</param>
    /// <returns>The corresponding byte array.</returns>
    public static byte[] ToByteArray(this String s)
    {
      return Encoding.UTF8.GetBytes(s);
    }

    /// <summary>
    /// Extension method that converts a String to a byte array 
    /// using teh specified Encoding.
    /// </summary>
    /// <param name="s">The String for which to generate the 
    /// byte array.</param>
    /// <param name="encoding">The encoding used to generate the 
    /// byte array.</param>
    /// <returns>The corresponding byte array.</returns>
    public static byte[] ToByteArray(this String s, Encoding encoding)
    {
      return encoding.GetBytes(s);
    }

    /// <summary>
    /// Extension method that creates a SHA1 Hash on a given String.
    /// </summary>
    /// <param name="s">The String for which to generate a 
    /// SHA1 Hash.</param>
    /// <returns>The SHA1 Hash for the given string.</returns>
    public static string ToSHA1Hash(this String s)
    {
      return BitConverter.ToString(SHA1Managed.Create().ComputeHash(s.ToByteArray()));
    }
  }
}